package online_store.model.bus;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import online_store.entity.CategoryEntity;
import online_store.model.dao.CategoryDao;
import online_store.model.dto.CategoryDTO;

@Service
public class CategoryBus {

	@Autowired
	private CategoryDao categoryDao;
	
	/*
	 * -1: Duplicated name
	 */
	@Transactional(value="jpaTransactionManager")
	public int createCategory(CategoryDTO dto){
		//validate duplicated user
		CategoryDTO existedCategory = findByName(dto.getName());
		if(existedCategory != null){
			return -1;
		}
		
		//create
		categoryDao.createCategory(convertDto2En(dto));
		
		return 1;
	}
	
	@Transactional(value="jpaTransactionManager")
	public List<CategoryDTO> findAll(){
		List<CategoryDTO> dto_list = new ArrayList<>();
		List<CategoryEntity> en_list = categoryDao.findAll();
		for(int i = 0; i < en_list.size(); i++){
			dto_list.add(convertEn2Dto(en_list.get(i)));
		}
		return dto_list;
	}
	
	@Transactional(value="jpaTransactionManager")
	public CategoryDTO getCategory(int categoryId){
		return convertEn2Dto(categoryDao.getCategory(categoryId));
	}
	
	@Transactional(value="jpaTransactionManager")
	public CategoryDTO findByName(String name){
		return convertEn2Dto(categoryDao.findByName(name));
	}
	
	@Transactional(value="jpaTransactionManager")
	private CategoryEntity convertDto2En(CategoryDTO dto){
		if(dto == null){
			return null;
		}
		CategoryEntity en = new CategoryEntity();
		en.setCategory_id(dto.getCategory_id());
		en.setName(dto.getName());
		return en;
	}
	
	@Transactional(value="jpaTransactionManager")
	private CategoryDTO convertEn2Dto(CategoryEntity en){
		if(en == null){
			return null;
		}
		CategoryDTO dto = new CategoryDTO();
		dto.setCategory_id(en.getCategory_id());
		dto.setName(en.getName());
		return dto;
	}
}
